import axios from "axios";
import _ from "lodash";
import {defineStore} from "pinia";
import {Howl} from "howler";
import {Constant, Lyrics, MyUrl, Song} from "./Constant.ts";
import {Qiniu_uploadFile} from "../plugins/qiniu.ts";


export class LyricLine {
    time
    data

    constructor(time, data) {
        this.time = time
        this.data = data
    }
}

export class LyricConfig {
    name
    data

    constructor(name, data) {
        this.name = name
        this.data = data
    }
}


// @ts-ignore
export function Lrc_loadLrcFile(filePath: string) {
    return axios.get(filePath).then((res) => {
        return res.data
    })
}


export async function Lrc_parse(filePath: string) {
    let res = await Lrc_loadLrcFile(filePath);
    return res.split(/[\r\n]+/).map((item) => {
        let regex = /^\[.*]/
        let match = item.match(regex);
        if (match) {
            //一条结果：说明是一个时间标签
            if (match.length == 1) {
                let m = match[0];
                //标准格式
                if (/\d+:\d+\.\d+/.test(m)) {
                    return new LyricLine(Lrc_parseTime(m.substring(1, m.length - 1)), item.substring(m.length, item.length))
                } else if (/[a-zA-Z]+:.*/i.test(m)) {
                    return new LyricConfig(m.substring(1, m.lastIndexOf(':')), item.substring(m.lastIndexOf(':') + 1, m.length - 1))
                }
            }
        }
    })
}

//将lrc格式的 【mm:ss.xx】 time转换为 毫秒
export function Lrc_parseTime(stringTime: string) {
    let re = /[0-9]+/g
    let match = stringTime.match(re);
    if (match) {
        return (_.parseInt(match[0].substring(0,2)) * 3600) + (_.parseInt(match[1].substring(0,2)) * 60) + (_.parseInt(match[2].substring(0,2)))
    }
}

export let Lrc_millisecondToLrcTime = (time: number) => {
    const minutes = Math.floor(time / 3600)
    const seconds = Math.floor(time % 3600 / 60)
    const milliseconds = Math.floor(time % 60)
    const padZero = (n: number) => (n < 10 ? '0' + n : n)
    return `${padZero(minutes)}:${padZero(seconds)}.${padZero(milliseconds)}`
}


export let useLyricsEditPlayerStore = defineStore('lyricsEditPlayer', {
    state: () => ({
        isPlaying: false,
        currentTime: 0,
        duration: 0,
        seekInterval: null,
        sound: null,
        src: null,
        isSeekChange: false,
    }),
    actions: {
        loadSound() {
            if (this.sound) {
                this.clearSeekInterval()
            }
            this.sound = new Howl({
                src: this.src,
                html5: true,
                autoplay: true,
                onload: () => {
                    console.log("sound开始加载")
                    // this.togglePlayPause()
                },
                onplay: () => {
                    console.log("sound开始播放")
                    this.isPlaying = true
                    this.duration = this.sound?.duration() * 60 ?? 0
                },
                onpause: () => {
                    console.log("sound暂停播放")
                    this.isPlaying = false
                },
                onstop: () => {
                    console.log("sound停止播放")
                    this.isPlaying = false
                    this.currentTime = 0
                },
                onend: () => {
                    console.log("sound完成播放")
                    this.isPlaying = false
                    this.currentTime = 0
                },
                onseek: () => {
                    console.log("seek发生变化")
                    //监听事件
                    this.currentTime = this.sound?.seek() * 60 ?? 0
                },
                onloaderror: (soundId, error) => {
                    console.error(`Error loading song: ${error}` + soundId)
                },
            })
            this.setSeekInterval()
        },
        pauseSound() {
            console.log("暂停")
            this.sound?.pause()
        },
        playSound() {
            if (!this.sound) {
                this.loadSound()
            } else {
                this.sound.play()
            }
        },
        togglePlayPause() {
            if (this.isPlaying) {
                this.pauseSound()
            } else {
                if (this.src) {
                    this.playSound();
                } else {
                    console.error("src为null");
                }
            }
        },
        seekSound(seek) {
            if (this.src) {
                console.log("跳过")
                this.sound?.seek(Math.floor(seek / 60))
            } else {
                console.error("src为null")
            }
        },
        stopSound() {
            if (this.sound) {
                this.sound.stop()
                this.sound = null
            }
            if (this.seekInterval) {
                this.clearSeekInterval()
            }
        },
        setSeekInterval() {
            if (!this.seekInterval) {
                console.log("加载interval")
                this.seekInterval = setInterval(() => {
                    if (!this.isSeekChange) {
                        this.currentTime = Math.floor(this.sound?.seek() * 60 ?? 0)
                    }
                }, 100)
            }
        },
        clearSeekInterval() {
            if (this.seekInterval) {
                console.log("已清除interval")
                clearInterval(this.seekInterval)
                this.seekInterval = null
            }
        }
    }
})


//TODO 数据库相关
export function Lyric_addLyrics(file:File,lyrics?:Lyrics,song?:Song) {
        //添加歌词
        lyrics.url = Qiniu_uploadFile(file, file.name, Constant.FOLDER_LRC);
        axios.post(MyUrl.LYRICS_addLyrics, JSON.stringify(lyrics), {
            headers: {
                "Content-Type": "application/json"
            }
        }).then((res) => {
            if(res.data.flag){
                //上传成功后再去update 当前歌曲
                song.lyricsId = res.data.data
                song.updatedAt = null
                axios.put(MyUrl.SONG_updateSong, JSON.stringify(song), {
                    headers: {
                        "Content-Type": "application/json"
                    }
                }).then((res)=>{
                    console.log(res.data)
                }).catch((error)=>{
                    console.error("上传歌词失败:" + error)
                })
            }
        }).catch((error) => {
            console.error("上传歌词失败:" + error)
        })
}

export function Lyric_getLyricsById(id:number,cb) {
    axios.get(MyUrl.LYRICS_getLyricsById,  {
        params:{
            id: id,
        }
    }).then((res) => {
        cb(res.data)
    }).catch((error) => {
        console.error("获取歌词失败:" + error)
    })

}

//更新
export function Lyric_updateLyrics(fileText:string,lyrics:Lyrics) {
    let file = stringToFile(fileText, "fileName.lrc", 'text/plain;charset=utf-8');
    let url = Qiniu_uploadFile(file, file.name, Constant.FOLDER_LRC);
    return axios.put(MyUrl.LYRICS_updateLyrics,lyrics, {
        params:{
            url:url
        },
        headers: {
            "Content-Type": "application/json"
        }
    }).then((res) => {
        if (res.data.flag) {

            return res.data.data
        }
    }).catch((error) => {
        console.error("获取歌词失败:" + error)
    });

}

export function stringToFile(str: string, fileName: string, contentType: string) {
    const blob = new Blob([str], {type: contentType})
    return new File([blob], fileName, {type: contentType})
}




